<?php


namespace App\Services;


use App\Models\Database as DatabaseModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class DBAPP
{
    const DB_NAME = 'app';
    /**
     * @return \Illuminate\Database\ConnectionInterface
     */
    static function db() {
        return DB::connection(self::DB_NAME);
    }

    /**
     * @return \Illuminate\Database\Schema\Builder
     */
    static function schema() {
        return Schema::connection(self::DB_NAME);
    }



    static function set_database($userId, $dbName = '') {
        $db = DatabaseModel::where('user_id', $userId)->where('default', 1)->first();
        if ($db) {
            $config = [
                'driver'    => $db->driver,
                'host'      => $db->db_host,
                'port'      => $db->db_port,
                'database'  => $dbName ?: $db->db_name,
                'username'  => $db->db_user,
                'password'  => $db->db_password,
                'charset'   => $db->db_charset,
                'collation' => $db->db_collation,
                'prefix'    => $db->frefix ?? ''
            ];

            app()->get('config')->set('database.connections.'.self::DB_NAME, $config);
            DB::purge(self::DB_NAME);
            DB::reconnect(self::DB_NAME);
        }
    }

    /**
     * 设置其他数据库
     * @param $db
     */
    static function set_other_database($db) {
        $config = [
            'driver'    => $db->driver,
            'host'      => $db->db_host,
            'port'      => $db->db_port,
            'database'  => $db->db_name,
            'username'  => $db->db_user,
            'password'  => $db->db_password,
            'charset'   => $db->db_charset,
            'collation' => $db->db_collation,
            'prefix'    => $db->frefix ?? ''
        ];

        app()->get('config')->set('database.connections.'.self::DB_NAME, $config);
        DB::purge(self::DB_NAME);
        DB::reconnect(self::DB_NAME);
    }

}
